// 沙盒环境工具函数
// 注意：这是一个模拟实现，实际生产环境中需要更安全的代码执行环境

// 模拟代码执行函数
export const executeCode = async (code, language) => {
  // 模拟执行延迟
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  try {
    let output = ''
    let executionTime = 0
    let memoryUsage = 0
    let status = 'success'
    
    switch (language) {
      case 'javascript':
        output = await executeJavaScript(code)
        break
      case 'python':
        output = await executePython(code)
        break
      case 'java':
        output = await executeJava(code)
        break
      case 'cpp':
        output = await executeCpp(code)
        break
      case 'go':
        output = await executeGo(code)
        break
      default:
        throw new Error(`不支持的语言: ${language}`)
    }
    
    // 模拟执行时间和内存使用
    executionTime = Math.floor(Math.random() * 1000) + 100
    memoryUsage = Math.floor(Math.random() * 50) + 10
    
    return {
      output,
      executionTime,
      memoryUsage,
      status
    }
    
  } catch (error) {
    return {
      output: `执行错误: ${error.message}`,
      executionTime: 0,
      memoryUsage: 0,
      status: 'error'
    }
  }
}

// JavaScript代码执行（模拟）
const executeJavaScript = async (code) => {
  // 安全检查
  if (containsUnsafeCode(code)) {
    throw new Error('代码包含不安全的内容')
  }
  
  try {
    // 创建一个安全的执行环境
    const sandbox = {
      console: {
        log: (...args) => args.join(' '),
        error: (...args) => args.join(' '),
        warn: (...args) => args.join(' '),
        info: (...args) => args.join(' ')
      },
      setTimeout: () => {},
      setInterval: () => {},
      fetch: () => Promise.resolve({}),
      XMLHttpRequest: () => {},
      eval: () => {},
      Function: () => {},
      window: undefined,
      document: undefined,
      localStorage: undefined,
      sessionStorage: undefined
    }
    
    // 使用Function构造函数创建执行环境
    const safeEval = new Function('console', 'setTimeout', 'setInterval', 'fetch', 'XMLHttpRequest', 'eval', 'Function', 'window', 'document', 'localStorage', 'sessionStorage', code)
    
    // 执行代码
    const result = safeEval(
      sandbox.console,
      sandbox.setTimeout,
      sandbox.setInterval,
      sandbox.fetch,
      sandbox.XMLHttpRequest,
      sandbox.eval,
      sandbox.Function,
      sandbox.window,
      sandbox.document,
      sandbox.localStorage,
      sandbox.sessionStorage
    )
    
    // 收集console输出
    let output = ''
    const originalLog = console.log
    const logs = []
    
    console.log = (...args) => {
      logs.push(args.join(' '))
    }
    
    // 重新执行以收集输出
    try {
      safeEval(
        sandbox.console,
        sandbox.setTimeout,
        sandbox.setInterval,
        sandbox.fetch,
        sandbox.XMLHttpRequest,
        sandbox.eval,
        sandbox.Function,
        sandbox.window,
        sandbox.document,
        sandbox.localStorage,
        sandbox.sessionStorage
      )
    } catch (e) {
      logs.push(`执行错误: ${e.message}`)
    }
    
    console.log = originalLog
    
    output = logs.join('\n')
    
    if (!output) {
      output = '代码执行完成，无输出'
    }
    
    return output
    
  } catch (error) {
    throw new Error(`JavaScript执行错误: ${error.message}`)
  }
}

// Python代码执行（模拟）
const executePython = async (code) => {
  // 安全检查
  if (containsUnsafeCode(code)) {
    throw new Error('代码包含不安全的内容')
  }
  
  // 模拟Python执行
  const output = []
  
  // 简单的Python代码解析和模拟执行
  const lines = code.split('\n')
  
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()
    
    if (line.startsWith('print(') && line.endsWith(')')):
      const content = line.slice(6, -1)
      if (content.startsWith('"') && content.endsWith('"')) {
        output.push(content.slice(1, -1))
      } else if (content.startsWith("'") && content.endsWith("'"):
        output.push(content.slice(1, -1))
      } else {
        // 简单的变量替换模拟
        output.push(`[变量输出: ${content}]`)
      }
    } else if (line.includes('=') && !line.includes('==')):
      // 变量赋值
      output.push(`[变量赋值: ${line}]`)
    } else if (line.startsWith('def ') || line.startsWith('class ')):
      // 函数或类定义
      output.push(`[定义: ${line}]`)
    } else if (line.startsWith('if ') || line.startsWith('for ') || line.startsWith('while ')):
      // 控制流
      output.push(`[控制流: ${line}]`)
    } else if (line && !line.startsWith('#')):
      // 其他非注释代码
      output.push(`[执行: ${line}]`)
    }
  }
  
  if (output.length === 0) {
    output.push('代码执行完成，无输出')
  }
  
  return output.join('\n')
}

// Java代码执行（模拟）
const executeJava = async (code) => {
  // 安全检查
  if (containsUnsafeCode(code)) {
    throw new Error('代码包含不安全的内容')
  }
  
  // 模拟Java执行
  const output = []
  
  // 简单的Java代码解析
  if (code.includes('System.out.println')) {
    const matches = code.match(/System\.out\.println\(([^)]+)\)/g)
    if (matches) {
      matches.forEach(match => {
        const content = match.slice(19, -1) // 移除 System.out.println( 和 )
        if (content.startsWith('"') && content.endsWith('"')) {
          output.push(content.slice(1, -1))
        } else {
          output.push(`[变量输出: ${content}]`)
        }
      })
    }
  }
  
  if (code.includes('public class')) {
    output.push('[Java类定义]')
  }
  
  if (code.includes('public static void main')) {
    output.push('[主方法定义]')
  }
  
  if (output.length === 0) {
    output.push('Java代码执行完成，无输出')
  }
  
  return output.join('\n')
}

// C++代码执行（模拟）
const executeCpp = async (code) => {
  // 安全检查
  if (containsUnsafeCode(code)) {
    throw new Error('代码包含不安全的内容')
  }
  
  // 模拟C++执行
  const output = []
  
  // 简单的C++代码解析
  if (code.includes('cout <<')) {
    const matches = code.match(/cout << ([^;]+);/g)
    if (matches) {
      matches.forEach(match => {
        const content = match.slice(7, -1) // 移除 cout << 和 ;
        if (content.startsWith('"') && content.endsWith('"')) {
          output.push(content.slice(1, -1))
        } else {
          output.push(`[变量输出: ${content}]`)
        }
      })
    }
  }
  
  if (code.includes('#include')) {
    output.push('[头文件包含]')
  }
  
  if (code.includes('int main()')) {
    output.push('[主函数定义]')
  }
  
  if (output.length === 0) {
    output.push('C++代码执行完成，无输出')
  }
  
  return output.join('\n')
}

// Go代码执行（模拟）
const executeGo = async (code) => {
  // 安全检查
  if (containsUnsafeCode(code)) {
    throw new Error('代码包含不安全的内容')
  }
  
  // 模拟Go执行
  const output = []
  
  // 简单的Go代码解析
  if (code.includes('fmt.Println')) {
    const matches = code.match(/fmt\.Println\(([^)]+)\)/g)
    if (matches) {
      matches.forEach(match => {
        const content = match.slice(12, -1) // 移除 fmt.Println( 和 )
        if (content.startsWith('"') && content.endsWith('"')) {
          output.push(content.slice(1, -1))
        } else {
          output.push(`[变量输出: ${content}]`)
        }
      })
    }
  }
  
  if (code.includes('package main')) {
    output.push('[Go包声明]')
  }
  
  if (code.includes('func main()')) {
    output.push('[主函数定义]')
  }
  
  if (output.length === 0) {
    output.push('Go代码执行完成，无输出')
  }
  
  return output.join('\n')
}

// 安全检查函数
const containsUnsafeCode = (code) => {
  const unsafePatterns = [
    /eval\s*\(/,
    /Function\s*\(/,
    /setTimeout\s*\(/,
    /setInterval\s*\(/,
    /fetch\s*\(/,
    /XMLHttpRequest/,
    /localStorage/,
    /sessionStorage/,
    /document\./,
    /window\./,
    /process\./,
    /require\s*\(/,
    /import\s+/,
    /__dirname/,
    /__filename/,
    /global/,
    /Buffer/,
    /child_process/,
    /fs\./,
    /os\./,
    /path\./,
    /crypto\./,
    /exec\s*\(/,
    /spawn\s*\(/,
    /execSync\s*\(/,
    /spawnSync\s*\(/
  ]
  
  return unsafePatterns.some(pattern => pattern.test(code))
}

// 获取支持的语言列表
export const getSupportedLanguages = () => {
  return [
    { value: 'javascript', label: 'JavaScript', icon: 'js' },
    { value: 'python', label: 'Python', icon: 'py' },
    { value: 'java', label: 'Java', icon: 'java' },
    { value: 'cpp', label: 'C++', icon: 'cpp' },
    { value: 'go', label: 'Go', icon: 'go' }
  ]
}

// 获取语言配置
export const getLanguageConfig = (language) => {
  const configs = {
    javascript: {
      extension: '.js',
      comment: '//',
      stringDelimiter: '"',
      keywords: ['function', 'const', 'let', 'var', 'if', 'else', 'for', 'while', 'return', 'class', 'import', 'export']
    },
    python: {
      extension: '.py',
      comment: '#',
      stringDelimiter: '"',
      keywords: ['def', 'class', 'if', 'else', 'elif', 'for', 'while', 'return', 'import', 'from', 'as']
    },
    java: {
      extension: '.java',
      comment: '//',
      stringDelimiter: '"',
      keywords: ['public', 'class', 'static', 'void', 'main', 'String', 'int', 'if', 'else', 'for', 'while', 'return']
    },
    cpp: {
      extension: '.cpp',
      comment: '//',
      stringDelimiter: '"',
      keywords: ['#include', 'int', 'main', 'cout', 'cin', 'if', 'else', 'for', 'while', 'return', 'class']
    },
    go: {
      extension: '.go',
      comment: '//',
      stringDelimiter: '"',
      keywords: ['package', 'import', 'func', 'main', 'var', 'const', 'if', 'else', 'for', 'range', 'return']
    }
  }
  
  return configs[language] || configs.javascript
}
